package com.example.impl;

import com.example.mapper.WxbCustomerMapper;
import com.example.mapper.WxbGoodsMapper;
import com.example.mapper.WxbGoodsSkuMapper;
import com.example.model.WxbCustomer;
import com.example.model.WxbGood;
import com.example.model.WxbGoodSku;
import com.example.model.util.PageUtils;
import com.example.model.vo.Result;
import com.example.util.GoodHandler;
import com.example.util.WxbGoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Set;
import java.util.UUID;

@Service
public class WxbGoodsServiceImpl implements WxbGoodsService {

    @Autowired
    private WxbGoodsMapper wxbGoodMapper;

    @Autowired
    private GoodHandler goodHandler;



    @Autowired
    private WxbCustomerMapper wxbCustomerMapper;

    @Autowired
    private WxbGoodsSkuMapper wxbGoodsSkuMapper;

    public void addGoodS(WxbGood goods){
        WxbCustomer wxbCustomer = (WxbCustomer) SecurityUtils.getSubject().getPrincipal();
        goods.setCustomerId(wxbCustomer.getCustomerId());
        String goodsId = wxbCustomer.getCustomerId() + System.currentTimeMillis();
        goods.setGoodId(goodsId);
        wxbGoodMapper.insertSelective(goods);
        List<WxbGoodSku> skus = goods.getSku();
        for (WxbGoodSku wxbGoodSku : skus) {
            wxbGoodSku.setSkuId("1"+ System.currentTimeMillis());
            wxbGoodSku.setGoodId(goodsId);
            wxbGoodSku.setSkuName(goods.getSkuName());
            wxbGoodSku.setSkuCost(goods.getSkuCost());
            wxbGoodSku.setSkuPrice(goods.getSkuPrice());
            wxbGoodSku.setSkuPmoney(goods.getSkuPmoney());
            wxbGoodsSkuMapper.insertSelective(wxbGoodSku);
        }

    }

    public PageUtils list(int pageNum){

        WxbGood goods = new WxbGood();
        int count = wxbGoodMapper.selectCount(goods);
        int pagesize = PageUtils.PAGE_SIZE;
        int pageCount = count%pagesize==0?count/pagesize:count/pagesize+1;
        List<WxbGood> goodList= goodHandler.getFromCache(pageNum);
        if(goodList == null) {
            synchronized (this) {
                goodList =  goodHandler.getFromCache(pageNum);
                if (goodList == null) {
                    System.out.println("--------------查询数据库");
                    goodList = wxbGoodMapper.listGoods((pageNum-1)*pagesize,pagesize);
                    goodHandler.addToCache(goodList,pageNum);
                    // 如果从数据库查询信息为null，则创建一个对象写入到缓冲，并设置过期时间
//                    if(goodList == null) {
//                        goodList = new ArrayList<>();
//                        item.setItemId(itemId);
//                        itemCacheHander.addItemToCacheEx(item);
//                    }else {
//                        itemCacheHander.addItemToCache(item);
//                    }

                }
            }
        }

       PageUtils page = new PageUtils();
       page.setPageCount(pageCount);
       page.setPageNum(pageNum);
       page.setData(goodList);
        return page;

    }

    public PageUtils listByType(String typeId,int pageNum){
        int pagesize = PageUtils.PAGE_SIZE;
        Example example = new Example(WxbGood.class);
        example.createCriteria().andEqualTo("typeId",typeId);
        int count =wxbGoodMapper.selectCountByExample(example);
        int pageCount =count%pagesize==0?count/pagesize:count/pagesize+1;

        List<WxbGood> goodList = wxbGoodMapper.listGoodsByType(typeId,(pageNum-1)*pagesize,pagesize);
        PageUtils page = new PageUtils();
        page.setPageNum(pageNum);
        page.setPageCount(pageCount);
        page.setData(goodList);

        return page;
    }

    public void updateState(int state,List<String>ids) throws Exception{
        for(String goodsId:ids){
            wxbGoodMapper.updateState(state,goodsId);
        }

    }


    public boolean saveGood(WxbGood wxbGood) {
        // 代码生成主键（注意：使用UUID，需要将wxb_good表中的主键的 长度 修改为 varchar(60)
        wxbGood.setGoodId(UUID.randomUUID().toString());
        //添加的商品，状态默认为“待审核 0”
        wxbGood.setState(0L);

        //下面四行代码在找到前端页面中的问题后删除！！！！！
        wxbGood.setSkuTitle(wxbGood.getSkuTitle().substring(1));
        wxbGood.setSkuCost(wxbGood.getSkuCost().substring(1));
        wxbGood.setSkuPrice(wxbGood.getSkuPrice().substring(1));
        wxbGood.setSkuPmoney(wxbGood.getSkuPmoney().substring(1));

        WxbCustomer wxbCustomer = (WxbCustomer) SecurityUtils.getSubject().getPrincipal();

        System.out.println(wxbCustomer.getCustomerId());

        wxbGood.setCustomerId(wxbCustomer.getCustomerId());
//
//            WxbGoodSku wxbGoodSku = new WxbGoodSku();
//            wxbGoodSku.setSkuId("1"+ System.currentTimeMillis());
//            wxbGoodSku.setGoodId(wxbGood.getGoodId());
//            wxbGoodSku.setSkuName(wxbGood.getSkuName().substring(1));
//            wxbGoodSku.setSkuCost(wxbGood.getSkuCost().substring(1));
//            wxbGoodSku.setSkuPrice(wxbGood.getSkuPrice().substring(1));
//            wxbGoodSku.setSkuPmoney(wxbGood.getSkuPmoney().substring(1));
//            wxbGoodsSkuMapper.insertSelective(wxbGoodSku);


        return wxbGoodMapper.insert(wxbGood) > 0;
    }


    public List<WxbGood> findGoodByParam(WxbGood param) {
        /*
         * 封装查询条件
         */
        Example example = new Example(WxbGood.class);
        if (param != null) {
            if (StringUtils.isNotBlank(param.getGoodName())) {
                example.and().andLike("goodName", "%" + param.getGoodName() + "%");
            }
            //根据价格区间进行查询
            //由于价格存储的是多个SKU的价格，且价格之间采用"|"分隔，所以查询时，可以先拆分，再查询
//        //由于价格是包含着多个SKU的价格，这时，考虑思路问题
//        if (StringUtils.isNotBlank(param.getSkuPrice())){
//            String[] prices = param.getSkuPrice().split("|");
//
//        }
            //根据state查询数据
            if (param.getState() != null) {
                example.and().andEqualTo("state", param.getState());
            }
        }


        //执行查询
        List<WxbGood> wxbGoods = wxbGoodMapper.selectByExample(example);


        return wxbGoods;
    }


    public Result updateStateByGoodId(String goodId, String state) {
        if (StringUtils.isNotBlank(goodId) && StringUtils.isNotBlank(state)) {
            //更新商品的状态
            WxbGood wxbGood = new WxbGood();
            wxbGood.setGoodId(goodId);
            wxbGood.setState(Long.parseLong(state));
            //调用更新方法
            boolean result = wxbGoodMapper.updateByPrimaryKeySelective(wxbGood) > 0;
            return new Result(result, result ? "操作成功" : "操作失败");
        }
        return new Result(false, "参数缺少,操作失败");
    }


    public void deleteByGoodId(List<String> goodId)throws Exception{

      Example example =new Example(WxbGood.class);
      example.createCriteria().andEqualTo("goodId",goodId);
      wxbGoodMapper.deleteByExample(example);
        goodHandler.deleteGood();
    }


    public List<WxbGood> wxbGoodList(){
        return wxbGoodMapper.selectAll();
    }

    @Override
    public List<WxbGood> findAll() {

        Example example1 = new Example(WxbGood.class);
        example1.createCriteria().andEqualTo("state",1L);
       List<WxbGood> WxbGood = wxbGoodMapper.selectByExample(example1);
        for (WxbGood good : WxbGood) {
            Example example = new Example(WxbGoodSku.class);
            example.createCriteria().andEqualTo("goodId",good.getGoodId());
            List<WxbGoodSku> skuList = wxbGoodsSkuMapper.selectByExample(example);
            good.setSku(skuList);
            good.setSkuString(getSkuList(skuList));

            //得到关联customer表里面的数据
            WxbCustomer customer = wxbCustomerMapper.selectByPrimaryKey(good.getCustomerId());
            good.setCustomerName(customer.getCustomerName());
            good.setLevel(customer.getLevel());
        }
        return WxbGood;

    }

    @Override
    public WxbGood findById(String goodId) {
        WxbGood good = wxbGoodMapper.selectByPrimaryKey(goodId);
        WxbCustomer customer = wxbCustomerMapper.selectByPrimaryKey(good.getCustomerId());
        Example example = new Example(WxbGoodSku.class);
        example.createCriteria().andEqualTo("goodId",goodId);
        List<WxbGoodSku> sku = wxbGoodsSkuMapper.selectByExample(example);
        good.setCustomerName(customer.getCustomerName());
        good.setQq(customer.getQq());
        good.setSku(sku);
        return good;
    }

    @Override
    public WxbGood findByAndId(String goodId) {
    WxbGood wxbGood = wxbGoodMapper.selectByPrimaryKey(goodId);
        Example example = new Example(WxbGoodSku.class);
        example.createCriteria().andEqualTo("goodId",goodId);
        List<WxbGoodSku> sku = wxbGoodsSkuMapper.selectByExample(example);
        wxbGood.setSku(sku);
        wxbGood.setSkuString(getSkuList(sku));
        return wxbGood;
    }


    private String getSkuList(List<WxbGoodSku> wxbGoodSku){
        StringBuffer sb = new StringBuffer();
        for (WxbGoodSku sku : wxbGoodSku) {
            sb.append(sku.getSkuName()+","+sku.getSkuPrice()+","+sku.getSkuPmoney()+".");
        }
        return sb.toString();
    }

}
